package com.ttj.service.impl;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.ttj.domain.oracle.WebValidationCode;
import com.ttj.mapper.oracle.WebValidationCodeMapper;
import com.ttj.service.WebValidationCodeService;
import com.ttj.util.BeanUtil;
import com.ttj.util.SendMessageUtil;
import com.ttj.vo.BaseRes;
@Service
public class WebValidationCodeServiceImpl implements WebValidationCodeService {

	@Resource
	private WebValidationCodeMapper codeMapper;
	
	@Override
	public BaseRes<WebValidationCode> buildVerify(String phone,int type) throws IOException {
		Random rnd = new Random();
		int num = rnd.nextInt(89999)+10000;
		WebValidationCode code = new WebValidationCode();
		String sn = "SDK-BBX-010-23933";
		String pwd = "7928318B";
		SendMessageUtil sm = new SendMessageUtil(sn, pwd);
		String content = URLEncoder.encode( "您的验证码是："+ num + ",仅用于注册校验（5分钟内有效）！" + "【绿猫网】", "utf8");
		sm.mdsmssend(phone, content, "", "", "", "");
		Date afterDate = new Date(new Date().getTime() + 300000);//5分钟
		int id = codeMapper.getId();
		code.setId(id+1);
		code.setCode(num+"");
		code.setType(type);//创建类型
		code.setPhonenum(phone);
		code.setExoireTime(afterDate);
		System.out.println("获取验证码："+code);
		codeMapper.buildVerify(code);
		BaseRes<WebValidationCode> baseRes = new BaseRes<WebValidationCode>();
		baseRes.setData(code);
		return baseRes;
	}

	@Override
	public BaseRes<WebValidationCode> checkVerify(String phone, String code,int type) {
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("phone", phone);
		map.put("vrify", code);
		map.put("type", type);
		List<WebValidationCode> checkVerify = codeMapper.checkVerify(map);
		BaseRes<WebValidationCode> baseRes = new BaseRes<WebValidationCode>();
		baseRes.setData(BeanUtil.voConvert(checkVerify, WebValidationCode.class));
		return baseRes;
	}

	@Override
	public int upd(String phone, String code) {
		WebValidationCode validation = new WebValidationCode();
		validation.setPhonenum(phone);
		validation.setCode(code);
		return codeMapper.upd(validation);
	}

}
